#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>

//MSB数据地址共14字节ACCEL_X、ACCEL_Y、ACCEL_Z、TEMP、GYRO_X、GYRO_Y、GYRO_Z每个两字节
static unsigned char findData(unsigned char data,int p_flag)
{
	unsigned char TM1638_LED[]={0x3F,0x06,0x5B,0x4F,0x66,0x6D,0x7D,0x07,0x7F,0x6F,0x77,0x7C,0x39,0x5E,0x79,0x71}; //0～F，1亮0灭
	unsigned char TM1638_LED_P[]={0xBF,0x86,0xDB,0xCF,0xE6,0xED,0xFD,0x87,0xFF,0xEF,0xF7,0xFC,0xB9,0xDE,0xF9,0xF1}; //0～F，1亮0灭

	if(p_flag ==0)
		return TM1638_LED[data];

	return TM1638_LED_P[data];
}

static void getData(short data, unsigned char *buff)
{
	int i=0;
	int temp =0;

	if(data <0)
	{
		buff[i++] = 0x40;
	}
	temp = abs(data);

	if(temp/10000) 
	{
		buff[i++] = findData(temp/10000, 0);
		temp = temp%10000;
		buff[i++] = findData(temp/1000, 0);
		temp = temp%1000;
		buff[i++] = findData(temp/100, 0);
		temp = temp%100;
		buff[i++] = findData(temp/10, 0);
		temp = temp%10;
		buff[i++] = findData(temp/1, 0);
	}
	else if(temp/1000) 
	{
		buff[i++] = findData(temp/1000, 0);
		temp = temp%1000;
		buff[i++] = findData(temp/100, 0);
		temp = temp%100;
		buff[i++] = findData(temp/10, 0);
		temp = temp%10;
		buff[i++] = findData(temp/1, 0);
	}
	else if(temp/100) 
	{
		buff[i++] = findData(temp/100, 0);
		temp = temp%100;
		buff[i++] = findData(temp/10, 0);
		temp = temp%10;
		buff[i++] = findData(temp/1, 0);
	}
	else if(temp/10) 
	{
		buff[i++] = findData(temp/10, 0);
		temp = temp%10;
		buff[i++] = findData(temp/1, 0);
	}
	else if(temp) 
	{
		buff[i++] = findData(temp/1, 0);
	}
}

int main(int argc, char **argv)
{
	int fd1=0;
	int fd2=0;
	int ret=0;
	static int i=0;
	unsigned char data[14]={0};
	short mpu6050Data[7] = {0};
	unsigned char dispBuff[9]={0};
	unsigned char ledPos[] = {0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80,0xff};

	if(argc !=3)
	{
		printf("Usage error %s\r\n",argv[0]);
		return -1;
	}

	fd1 = open(argv[1],O_RDWR);
	if(fd1 <0)
	{
		printf("open file:%s error\r\n",argv[1]);
		return -1;
	}

	fd2 = open(argv[2],O_RDWR);
	if(fd2 <0)
	{
		printf("open file:%s error\r\n",argv[2]);
		return -1;
	}

	while(1)
	{
		ret = read(fd1, data, sizeof(data));
		if(ret <0)
		{
			printf("read error! ret:%d\r\n",ret);
			break;
		}

		mpu6050Data[0] = (data[0]<<8) +data[1];
		mpu6050Data[1] = (data[2]<<8) +data[3];
		mpu6050Data[2] = (data[4]<<8) +data[5];
		mpu6050Data[3] = ((data[6]<<8) +data[7])/340.0+36.53;
		mpu6050Data[4] = (data[8]<<8) +data[9];
		mpu6050Data[5] = (data[10]<<8) +data[11];
		mpu6050Data[6] = (data[12]<<8) +data[13];

		memset(dispBuff, 0, 9);
		dispBuff[8] = ledPos[i];
		getData(mpu6050Data[i++],dispBuff);
		if(i>6) i=0;

		ret = write(fd2,dispBuff,9);
		if(ret <0)
		{
			printf("write error! ret:%d\r\n",ret);
			break;
		}
		
		sleep(1);
	}
	
	close(fd1);
	close(fd2);

	return 0;
}


